package cn.moonspace.flowerowner.service.impl;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cn.moonspace.common.util.MyJsonUtil;
import cn.moonspace.flowerowner.entities.Car;
import cn.moonspace.flowerowner.exception.DriverException;
import cn.moonspace.flowerowner.service.CarService;

@Service("carService")
public class CarServiceImpl extends BaseService implements CarService { 

	@Override
	public JSONObject findCars(int pages, int pageSize) throws DriverException {
		JSONObject result = new JSONObject();

		Pageable pageable = new PageRequest(pages, pageSize);
		
		Page<Car> cars = carRepository.findAll(pageable);
		
		List<Car> results = new ArrayList<Car>();
		
		for(Car car : cars.getContent()){
			try {
				results.add(car.clone());
			} catch (CloneNotSupportedException e) {
				DriverException de = new DriverException(DriverException.CarCloneException, "Car Clone Error: " + e.getMessage(), this.getClass().getName());
				de.setStackTrace(e.getStackTrace());
				throw de;
			}
		}
		JSONArray arrUploads = JSONArray.fromObject(results, MyJsonUtil.getConfig());
		result.put("results", arrUploads);
		
		return result;
	}
}
